import UpdateModal from '@/pages/Admin/Link/components/UpdateModal';
import { deleteUrlRelateUsingPost} from '@/services/backend/shortLinkController';
import { listLinkByPageUsingPost } from '@/services/backend/userController';
import type { ActionType, ProColumns} from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Space, Typography,Popconfirm,Table, Switch, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { SUCCESS_CODE } from '@/constants/index';

/**
 * 链接管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.PageUrlVo_>();

  // 批量删除
  const handleDelete = async (row: any) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      const res = await deleteUrlRelateUsingPost(row);
      hide();
      message.success(res.message);
      actionRef?.current?.reload();
      return true;
    } 
    catch (error: any) {
      hide();
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.PageUrlVo_>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '链接状态',
      dataIndex: 'status',
      render: (_, record) => {
        let tag;
        if(record.status === 0) {
          tag = <Tag color="orange">草稿</Tag>;
        } else if(record.status === 1) {
          tag = <Tag color="red">发布</Tag>;
        } else if(record.status === 2) {
          tag = <Tag color="gray">禁用</Tag>;
        }
        return tag;
      },
      hideInSearch: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'text',
    },
    {
      title: '图标',
      dataIndex: 'urlImg',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '短链',
      dataIndex: 'sortUrl',
      valueType: 'textarea',
    },
    {
      title: '访问次数',
      dataIndex: 'visits',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '允许访问次数',
      dataIndex: 'allowNum',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '是否私密',
      dataIndex: 'privateTarget',
      render: (_, record) => {
        return <Switch checked={record.privateTarget===2 || false} />;
      },
      hideInSearch: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title={'❌删除链接'}
            description="确定要删除此链接吗？"
            onConfirm={() => handleDelete(record.id?[record.id]:[])}
            okText="确定"
            cancelText="取消"
          >
             <Typography.Link type="danger">
              删除
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.PageUrlVo_>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id"
        pagination={{
          pageSize: 5,
        }}
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {
          const query = {
            title: params.title,
            sortUrl: params.sortUrl,
            userId: 0,
            privateTarget: params.privateTarget || 0,
            page: params.current,
            pageSize: params.pageSize,
          }
          const res = await listLinkByPageUsingPost(query);
          return {
            success: res.code === SUCCESS_CODE,
            data: res.data?.data || [],
            total:res.data?.total || 0,
          };
        }}
        columns={columns}
      />
      <UpdateModal
        visible={updateModalVisible}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default UserAdminPage;
